import json
from urllib.parse import quote
import requests


def getlnglat(address, ak):
    url = 'http://api.map.baidu.com/geocoding/v3/'
    output = 'json'
    address = quote(address)  # 由于本文地址变量为中文，为防止乱码，先用quote进行编码
    uri = url + '?' + 'address=' + address + '&output=' + output + '&ak=' + ak + '&callback=showLocation%20' + '//GET%E8%AF%B7%E6%B1%82'
    res = requests.get(uri).text
    temp = json.loads(res)  # 将字符串转化为json
    lat = temp['result']['location']['lat']
    lng = temp['result']['location']['lng']
    return lat, lng  # 纬度 latitude,经度 longitude


ak = ''
f = open("address.txt", "w", encoding="utf8")
for line in open("result.txt", encoding="utf8"):
    lat, lng = getlnglat(line.replace("\n", ""), ak)
    f.write(str(lat) + "," + str(lng) + "\n")
